package hng.interceptor;

import hng.enums.BizCodeEnum;
import hng.model.LoginUser;
import hng.util.CommonUtil;
import hng.util.JWTUtil;
import hng.util.JsonData;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import hng.util.RedisUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    public static ThreadLocal<LoginUser> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null) {
            token = request.getParameter("token");
        }

        // token为空 用户未登录
        if (!StringUtils.isNotBlank(token)) {
            CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
            return false;
        }

        Claims claims = JWTUtil.checkJWT(token);
        if (claims == null ){
            log.info("未登录");
            //未登录
            CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
            return false;
        }

        Integer userId = Integer.valueOf(claims.get("id").toString());
        String phone = (String) claims.get("phone");
        Integer role = Integer.valueOf(claims.get("role").toString());
        Integer storeId = Integer.valueOf(claims.get("storeId").toString());

        // 判断用户请求路径是否包含 /api/store
        if (request.getRequestURI().contains("/api/store") && role != 2) {
            log.info("用户角色不允许访问此路径");
            CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.NO_ADMIN));
            return false;
        }

        // 判断用户请求路径是否包含 /api/admin
        if (request.getRequestURI().contains("/api/admin") && role != 3) {
            log.info("用户角色不允许访问此路径");
            CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.NO_ADMIN));
            return false;
        }

        LoginUser loginUser = LoginUser
                .builder()
                .id(userId)
                .phone(phone)
                .role(role)
                .storeId(storeId)
                .build();

        // 判断请求接口的路径是否包含/admin
        /**
         * 如果是 就判断用户role是否为管理员角色
         * 如果用户的role不是管理员 就
         *      CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
         *      弹出异常，输入数据
         *      return false;
         */


        // 用户异地登录
//        try {
//            String redisToken = (String) RedisUtil.redis.opsForValue().get("hng:token:" + loginUser.getId().toString());
//            if (!token.equals(redisToken)){
//                CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_LGIN_ANYWHERE));
//                return false;
//            }
//        } catch (NullPointerException e) {
//            CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
//            return false;
//        }

        // 通过threadLocal线程池传递用户登录信息
        threadLocal.set(loginUser);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
